package com.azzcs.customer.utils;


import com.alibaba.druid.pool.DruidDataSource;
import com.azzcs.spring.anno.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author: wzg
 * @Date: 2020/12/13 下午5:34
 */
@Component
public class ConnectionUtils {

    private DataSource dataSource;

    public ConnectionUtils() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/bank");
        dataSource.setUsername("root");
        dataSource.setPassword("azzcs");
        this.dataSource = dataSource;
    }

    private ThreadLocal<Connection> local = new ThreadLocal<>();

    public Connection getConnection() throws SQLException {
        Connection connection = local.get();
        if(connection == null){
            connection = dataSource.getConnection();
            local.set(connection);
        }
        return connection;
    }
}
